import 'dart:convert'  as convert;
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';//从相册里面选择图片或者拍照获取照片
import 'package:flutterapp/fileUpload/succeed.dart';
import 'package:flutterapp/fileUpload/next.dart';
import 'package:flutterapp/fileUpload/demo.dart';

class PhotoPage extends StatefulWidget {
  @override
  _PhotoPageState createState() => _PhotoPageState();
}

class _PhotoPageState extends State<PhotoPage> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this._getImageFromGallery();
  }

  //记录选择的照片
  File image;

  //当图片上传成功后，记录当前上传的图片在服务器中的位置
  String _imgServerPath;

  //相册选择
  Future _getImageFromGallery() async {
    var image1 = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      image = image1;
    });
  }

  //上传图片到服务器
  _uploadImage() async {
    String oriTxt =  image.path;
    Future image2base64 = Util.image2Base64(oriTxt);
    String code = "";
    bool isComplete = false;
    image2base64.then((value) {
      code = value;
    }).whenComplete((){
      print("异步任务处理完成:${code}");
      isComplete = true;
      _test(code);
    });
  }

  _test(String code) async{
    Map map = {
      "sole_code":"bc96e08c-ae0b-4ba1-a777-f8dbfc2ba5c1",
      "init_img": "data:image/png;base64,"+code,
      "specification_code":"005"
    };

    Response response = await Dio().post("http://z.qingchan.vip:8086/api", data: map);
    print(response);
    if (response.statusCode == 200) {
      Map responseData = response.data;
      print("http://z.qingchan.vip:8086/api${responseData['init_img']}");
      setState(() {
        this._imgServerPath = "http://z.qingchan.vip:8086/api${responseData['init_img']}";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('选择照片'),
        ),
        body: ListView(
          children: <Widget>[
            Center(
              child: Column(
                children: <Widget>[
                  image == null ?
                  Center(
                    child: Column(
                      children: <Widget>[
                        Container(
                          width: 150,
                          height: 40,
                          child: OutlineButton(
                            borderSide: BorderSide(
                              color: Theme.of(context).primaryColor,
                            ),
                            color: Colors.blueAccent,
                            child: Text(
                              '请上传证件照',
                              style: TextStyle(
                                fontSize: 20,
                                color: Colors.blue,
                              ),
                            ),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(5),
                            ),
                            onPressed: (){
                              this._getImageFromGallery();
                            },
                          ),
                        )
                      ],
                    ),
                  )


                      :
                  Container(
                    height: 650,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Column(
                          children: <Widget>[
                            Container(
                              width: 200,
                              height: 200,
                              child: Image.file(
                                  image,fit:BoxFit.contain
                              ),
                            ),
                            Container(
                              width: 230,
                              child: Image.asset('images/fileUpload/7.png'),
                            ),
                          ],
                        ),

                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Container(
                              width: 150,
                              height: 40,
                              child: OutlineButton(
                                borderSide: BorderSide(
                                  color: Theme.of(context).primaryColor,
                                ),
                                color: Colors.blueAccent,
                                child: Text(
                                  '重新上传',
                                  style: TextStyle(fontSize: 20, color: Colors.blue,),),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(5),
                                ),
                                onPressed: (){
                                  _getImageFromGallery();
                                  },
                              ),
                            ),
                            Container(
                              width: 150,
                              height: 40,
                              child: FlatButton(
                                color: Colors.blueAccent,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(5),
                                ),
                                child: Text(
                                  '提交预审',
                                  style: TextStyle(fontSize: 20, color: Colors.white),
                                ),
                                onPressed: (){
                                  _uploadImage();
                                  FinishAnimation.show(context);

                                  Future.delayed(Duration(seconds: 2), () {
                                    Navigator.of(context).push(
                                        MaterialPageRoute(
                                          builder: (context)=>Next(image: this.image,),
                                        )
                                    );
                                  });
                                },
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Util{
  /*
  * 通过图片路径将图片转换成Base64字符串
  */
  static Future image2Base64(String path) async {
    File file = new File(path);
    List<int> imageBytes = await file.readAsBytes();
    return convert.base64Encode(imageBytes);
  }
}